﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml;

namespace TestesFixacao.Framework.Extensions
{
    public static class XmlReaderExtensions
    {
        /// <summary>
        /// Realiza a contagem de ocorrências da tag pesquisada.
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="tagMae"></param>
        /// <param name="tagPesquisada"></param>
        /// <param name="numeroOcorrencias"></param>
        /// <returns></returns>
        public static XmlTextReader ElementCount(this XmlTextReader reader, string tagMae, 
            string tagPesquisada, ref int numeroOcorrencias)
        {
            reader.Read();

            var strXml = reader.ReadInnerXml();

            strXml = string.Format("<{0}>{1}</{0}>", tagMae, strXml);

            numeroOcorrencias = ContaTag(strXml, tagPesquisada);

            var readerAux = new XmlTextReader(new StringReader(strXml));

            return readerAux;
        }
        
        private static int ContaTag(string node, string tag)
        {
            var reader = new XmlTextReader(new StringReader(node));

            int i = 0;

            while (reader.ReadToFollowing(tag)) i++;

            return i;
        }
    }
}
